package com.jzo2o.market.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.model.Result;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.NumberUtils;
import com.jzo2o.market.mapper.ActivityMapper;
import com.jzo2o.market.model.domain.Activity;
import com.jzo2o.market.model.dto.request.ActivityQueryForPageReqDTO;
import com.jzo2o.market.model.dto.request.ActivitySaveReqDTO;
import com.jzo2o.market.model.dto.response.ActivityInfoResDTO;
import com.jzo2o.market.service.IActivityService;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.market.service.ICouponWriteOffService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-16
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements IActivityService {
    private static final int MILLION = 1000000;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ICouponService couponService;

    @Resource
    private ICouponWriteOffService couponWriteOffService;

    @Resource
    private ActivityMapper activityMapper;

    @Resource
    private IActivityService activityService;


    /**
     * 分页查询优惠券活动
     */
    @Override
    public PageResult<Activity> ispage(ActivityQueryForPageReqDTO activityQueryForPageReqDTO) {
        // 创建分页对象
        Page<Activity> page = Page.of(activityQueryForPageReqDTO.getPageNo(), activityQueryForPageReqDTO.getPageSize());

        // 构建查询条件
        LambdaQueryChainWrapper<Activity> queryWrapper = lambdaQuery()
                .like(StringUtils.hasText(activityQueryForPageReqDTO.getName()), Activity::getName, activityQueryForPageReqDTO.getName())
                .eq(activityQueryForPageReqDTO.getStatus() != null, Activity::getStatus, activityQueryForPageReqDTO.getStatus())
                .eq(activityQueryForPageReqDTO.getType() != null, Activity::getType, activityQueryForPageReqDTO.getType())
                .eq(activityQueryForPageReqDTO.getId() != null, Activity::getId, activityQueryForPageReqDTO.getId())
                .orderByDesc(Activity::getCreateTime);

        // 执行分页查询
        Page<Activity> resultPage = queryWrapper.page(page);

        // 封装PageResult
        PageResult<Activity> pageResult = PageResult.of(
                resultPage.getRecords(),
                Math.toIntExact(resultPage.getSize()),
                resultPage.getPages(),
                resultPage.getTotal()
        );
        return pageResult;

    }

    /**
     * 增或修改优惠券活动
     */
    @Override
    @Transactional
    public Result<Void> addsave(ActivitySaveReqDTO activitySaveReqDTO) {
        //设置库存

        if (activitySaveReqDTO.getType() == 2 &&
                (activitySaveReqDTO.getDiscountRate() == null || activitySaveReqDTO.getDiscountRate() <= 0)) {
            throw new IllegalArgumentException("折扣类型必须设置有效的折扣率");
        }

        // type为1时,设置discountRate为0
        if (activitySaveReqDTO.getType() == 1 && activitySaveReqDTO.getDiscountRate() == null) {
            activitySaveReqDTO.setDiscountRate(0);
        }
        // 获取数据库中该ID的优惠券活动状态不为1不能修改
        if (activitySaveReqDTO.getId() != null) {
            Activity activity = activityService.getById(activitySaveReqDTO.getId());
            if (activity != null && activity.getStatus() != 1) {
                throw new RuntimeException("非生效状态的活动不能修改");
            }
        }
        // 执行数据库操作,如果数据库有数据，则执行更新操作，否则执行插入操作
        if (activitySaveReqDTO.getId() == null) {
            // 设置ID
            activitySaveReqDTO.setId(IdUtil.getSnowflakeNextId());
            int result = activityMapper.addsave(activitySaveReqDTO);
        } else {
            int result = activityMapper.upById(activitySaveReqDTO);
        }
        return Result.ok();
    }

    /**
     * 根据ID查询优惠劵活动详情
     */
    @Override
    public ActivityInfoResDTO getupById(Long id) {
        // 1.获取活动
        Activity activity = baseMapper.selectById(id);
        // 判空
        if (activity == null) {
            return new ActivityInfoResDTO();
        }
        // 2.数据转换，并返回信息
        ActivityInfoResDTO activityInfoResDTO = BeanUtils.toBean(activity, ActivityInfoResDTO.class);
        // 设置状态
//        activityInfoResDTO.setStatus(getStatus(activity.getDistributeStartTime(), activity.getDistributeEndTime(), activity.getStatus()));
        // 3.领取数量
//        Integer receiveNum = couponService.countReceiveNumByActivityId(activity.getId());
        Integer receiveNum = activity.getTotalNum() - activity.getStockNum();
        activityInfoResDTO.setReceiveNum(receiveNum);
        // 4.核销量
        Integer writeOffNum = couponWriteOffService.countByActivityId(id);
        activityInfoResDTO.setWriteOffNum(NumberUtils.null2Zero(writeOffNum));

        //
        return activityInfoResDTO;
    }

    /**
     * 撤销活动
     */
    @Override
    public Result<Void> addrasd(Long id) {
        ActivityInfoResDTO activity = activityService.getupById(id);
        if (activity == null) {
            throw new RuntimeException("活动不存在");
        }
        if (activity.getStatus() != 1) {
            throw new RuntimeException("非生效状态的活动不能撤销");
        }
        activity.setStatus(3);
        int result = activityMapper.updateById(activity);
        return result > 0 ? Result.ok() : Result.error("撤销活动失败");
    }

    @Override
    public void updateActivityStatusToOngoing() {
        // 查询当前时间大于开始时间且状态为未开始(假设状态1为未开始)的活动，更新为进行中(假设状态2为进行中)
        lambdaUpdate()
                .eq(Activity::getStatus, 1)
                .lt(Activity::getDistributeStartTime, LocalDateTime.now())
                .set(Activity::getStatus, 2)
                .update();
    }

    @Override
    public void updateActivityStatusToInvalid() {
        // 查询当前时间大于结束时间且状态为进行中(状态2)的活动，更新为已失效(假设状态3为已失效)
        lambdaUpdate()
                .eq(Activity::getStatus, 2)
                .lt(Activity::getDistributeEndTime, LocalDateTime.now())
                .set(Activity::getStatus, 3)
                .update();
    }

}
